import api from './api'

export const authService = {
  // 用户注册
  async register(userData) {
    try {
      const response = await api.post('/auth/register', userData)
      const { access_token, user } = response.data
      
      // 保存token和用户信息到本地存储
      localStorage.setItem('token', access_token)
      localStorage.setItem('user', JSON.stringify(user))
      
      return { success: true, user, token: access_token }
    } catch (error) {
      return {
        success: false,
        error: error.response?.data?.message || '注册失败'
      }
    }
  },

  // 用户登录
  async login(credentials) {
    try {
      const response = await api.post('/auth/login', credentials)
      const { access_token, user } = response.data
      
      // 保存token和用户信息到本地存储
      localStorage.setItem('token', access_token)
      localStorage.setItem('user', JSON.stringify(user))
      
      return { success: true, user, token: access_token }
    } catch (error) {
      return {
        success: false,
        error: error.response?.data?.message || '登录失败'
      }
    }
  },

  // 用户登出
  logout() {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  },

  // 获取当前用户信息
  getCurrentUser() {
    const user = localStorage.getItem('user')
    return user ? JSON.parse(user) : null
  },

  // 检查是否已登录
  isAuthenticated() {
    return !!localStorage.getItem('token')
  },

  // 获取token
  getToken() {
    return localStorage.getItem('token')
  }
}
